/**
 * @description
 * dotnar跨域上传上传:点击按钮,直接选择文件上传
 * @author Jinqn
 * @date 2014-03-31
 */
;
(function() {
    var utils = baidu.editor.utils;
    var editorui = baidu.editor.ui;
    var domUtils = baidu.editor.dom.domUtils;
    var domUtils = baidu.editor.dom.domUtils;


    UE.plugin.register('coajaxupload', function() {
        var me = this,
            isLoaded = false,
            containerBtn;

        function initUploadBtn() {
            var w = containerBtn.offsetWidth || 20,
                h = containerBtn.offsetHeight || 20,
                wrapper = document.createElement('div'),
                btnStyle = 'display:block;width:' + w + 'px;height:' + h + 'px;overflow:hidden;border:0;margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;cursor:pointer;';



            var timestrap = (+new Date()).toString(36);

            wrapper.innerHTML = '<input id="edui_input_' + timestrap + '" type="file" accept="image/*" name="' + me.options.imageFieldName + '" ' +
                'style="' + btnStyle + '">';

            wrapper.className = 'edui-' + me.options.theme;
            wrapper.id = me.ui.id + '_coajaxupload';

            var input = wrapper.getElementsByTagName('input')[0];
            var loading_img_url = this.options.themePath + this.options.theme + '/images/loading.gif';

            require(["jQuery", "coAjax", "localResizeIMG"], function($, coAjax) {
                $inputNode = $(input);
                $inputNode.localResizeIMG({
                    maxWidth: 1024,
                    quality: 0.8,
                    // before: function () {},
                    success: function(result) {
                        var loadingId = 'loading_' + (+new Date()).toString(36);
                        me.execCommand('inserthtml', '<img id="' + loadingId + '" src="' + loading_img_url + '"></span>', true);

                        function showErrorLoader(title) {
                            if (loadingId) {
                                var loader = me.document.getElementById(loadingId);
                                loader && domUtils.remove(loader);
                                me.fireEvent('showmessage', {
                                    'id': loadingId,
                                    'content': title,
                                    'type': 'error',
                                    'timeout': 4000
                                });
                            }
                        }

                        //使用BASE64上传
                        coAjax.post(appConfig.other.upload_base64_image, {
                            img_base64: result.base64
                        }, function(result) {
                            var img_url = appConfig.img_server_url + result.result.key;
                            var loader = me.document.getElementById(loadingId);
                            loader.src = img_url;
                            // domUtils.remove(loader);
                        }, function(errorCode, xhr, errorMsg) {
                            showErrorLoader(errorMsg);
                        }, function() {
                            showErrorLoader("网络异常，请重试！")
                        });
                    }
                });
            });

            wrapper.style.cssText = btnStyle;
            containerBtn.appendChild(wrapper);
        }

        return {
            bindEvents: {
                'ready': function() {
                    //设置loading的样式
                    utils.cssRule('loading',
                        '.loadingclass{display:inline-block;cursor:default;background: url(\'' + this.options.themePath + this.options.theme + '/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
                        '.loaderrorclass{display:inline-block;cursor:default;background: url(\'' + this.options.themePath + this.options.theme + '/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
                        '}',
                        this.document);
                },
                /* 初始化简单上传按钮 */
                'coajaxuploadbtnready': function(type, container) {
                    containerBtn = container;
                    me.afterConfigReady(initUploadBtn);
                }
            },
            outputRule: function(root) {
                utils.each(root.getNodesByTagName('img'), function(n) {
                    if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
                        n.parentNode.removeChild(n);
                    }
                });
            },
            commands: {
                'coajaxupload': {
                    queryCommandState: function() {
                        return 0;
                    }
                }
            }
        }
    });



    editorui.coajaxupload = function(editor) {
        var name = 'coajaxupload',
            ui = new editorui.Button({
                className: 'edui-for-' + "simpleupload",
                title: editor.options.labelMap[name] || editor.getLang("labelMap." + name) || '',
                onclick: function() {},
                theme: editor.options.theme,
                showText: false
            });
        editorui.buttons[name] = ui;
        editor.addListener('ready', function() {
            var b = ui.getDom('body'),
                iconSpan = b.children[0];
            editor.fireEvent('coajaxuploadbtnready', iconSpan);
        });
        return ui;
    };

}());